/**

 * Description Build
 * Power By Mr.K
 * Copyright www.cnkk.me

 Please respect the developers, thank you.

 */

require('shelljs/global');

var path = require("path");
var webpack = require('webpack');
var webpackConfig = require('./webpack.config.js');

//定义Public保留的文件资源
var unDelete = ['down', 'snap', 'static'];

//获得参数
var BUILD_TYPE = process.argv.slice(2).join('') == 'online' ? 'online' : 'dev';

//判断是否在数组
var inArray = function(str, arr){

    if(!arr && typeof arr != 'object') return false;

    for(var i=0;i<arr.length;i++){
        if(arr[i] == str) return true;
    }

    return false;

};

//向控制台输出编译后信息
var outProcess = function(err, stats){

    if (err) throw err;

    process.stdout.write('\n');
    process.stdout.write(stats.toString({
            colors: true,
            modules: false,
            children: false,
            chunks: false,
            chunkModules: false
        }) + '\n');

};

//输出初始信息
process.stdout.write(
    '  \n' +
    '  * Project: vue-webframe\n' +
    '  * Copyright: www.cnkk.me\n' +
    '  * Building: '+ BUILD_TYPE +'\n' +
    '  \n' +
    '  Task begin...\n\n'
);

rm('-rf', './output');

process.stdout.write(
    '  File clean up successful...\n\n'
);

/**
 * 编译模式
 */
if(BUILD_TYPE == 'online'){  //线上

    var config = webpackConfig;

    var plugin = [

        //开启压缩
        new webpack.optimize.UglifyJsPlugin({
            compress: {
                warnings: false
            }
        })

    ];

    //增加指纹功能
    config.output.chunkFilename = "lib/[chunkhash:8].bundle.js";

    config.module.loaders.forEach(function(d, i){
        if(d.name == 'image'){
            config.module.loaders[i].query.name = "/images/[name].[ext]?[hash:8]";
        }
    });

    config.plugins.forEach(function(d, i){
        if(d.options && d.options.name == 'html'){
            config.plugins[i].options.hash = true;
        }
    });

    //替换线上文件版本
    config.resolve.alias.vue = path.join(__dirname, "./web/lib/vue/vue.min.js");
    config.resolve.alias.echarts = path.join(__dirname, "./web/lib/echarts/echarts.js");

    config.plugins = config.plugins.concat(plugin);

    var compiler = webpack(config);

    compiler.run(outProcess);

}else{  //开发

    var config = webpackConfig;

    var plugin = [

        //热加载
        new webpack.HotModuleReplacementPlugin(),
        new webpack.NoErrorsPlugin()

    ];

    config.plugins = config.plugins.concat(plugin);

    var compiler = webpack(config);

    //监听
    compiler.watch({
        aggregateTimeout: 300,
        poll: true
    }, outProcess);

}